import {ProjectModel} from '../modal/ProjectModel'
import {checkFavorite} from '../util/Utils'

/**
 *
 * @param actionType
 * @param dispatch
 * @param storeName
 * @param data
 * @param pageSize
 */
export const handleData = (actionType, dispatch, storeName, data, pageSize, favoriteDao) => {
    let fixItems = []

    if (data && data.data) {
        if (Array.isArray(data.data)) {
            fixItems = data.data
        } else if (Array.isArray(data.data.items)) {
            fixItems = data.data.items
        }
    }
    //第一次要加载的数据
    let showItems = pageSize > fixItems.length ? fixItems : fixItems.slice(0, pageSize);
    _projectModels(showItems, favoriteDao, projectModels => {
        dispatch({
            type: actionType,
            items: fixItems,
            projectModels,
            storeName,
            pageIndex: 1,
        })
    })

}

export async function _projectModels(showItems, favoriteDao, callBack) {
    let keys = []
    try {
        keys = await favoriteDao.getFavoriteKeys()
    } catch (e) {
        console.log('_projectModels', e)
    }
    let projectModels = []
    for (let i = 0, len = showItems.length; i < len; i++) {
        let isFavorite = checkFavorite(showItems[i], keys, favoriteDao)
        projectModels.push(new ProjectModel(showItems[i], isFavorite))
    }
    typeof callBack === 'function' && callBack(projectModels)
}
